<template>
  <div class="container">
    <div class="panel" :loading="true">
      <div class="mainbox">
        <div class="newdatebox"
          >数据概览 <span>时间截止日期:{{ currentTime }}</span></div
        >
        <div class="newboxmide">
          <div class="newboxleftitem">
            <div class="skitem">
              <div class="skitemimg">
                <img src="@/assets/images/sj1.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">教室总数量</div>
                <div class="skitemdesn"
                  ><span>{{ datad.roomNumber }}</span
                  >间</div
                >
              </div>
            </div>
            <div class="skitem skitems" @click="goToAboutPage('class')">
              <div class="skitemimg">
                <img src="@/assets/images/sj1.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">课程占用教室</div>
                <div class="skitemdesn"
                  ><span>{{ datad.courseRoomNumber }}</span
                  >间</div
                >
              </div>
            </div>
          </div>
          <div class="newboxleftitem">
            <div class="skitem skitems" @click="goToAboutPage('devicebooking')">
              <div class="skitemimg">
                <img src="@/assets/images/sj2.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">今日设备借用</div>
                <div class="skitemdesn"
                  ><span>{{ datad.todayDeviceNumber }}</span
                  >个</div
                >
              </div>
            </div>
            <div class="skitem skitems">
              <div class="skitemimg" @click="goToAboutPage('devicebooking')">
                <img src="@/assets/images/sj2.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">明日设备借用</div>
                <div class="skitemdesn"
                  ><span>{{ datad.tomorrowDeviceNumber }}</span
                  >个</div
                >
              </div>
            </div>
          </div>
        </div>
        <div class="newboxmide">
          <div class="newboxleftitem">
            <div class="skitem">
              <div class="skitemimg">
                <img src="@/assets/images/sj3.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">预约在用人数 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.appointmentNumber }}</span
                  >人</div
                >
              </div>
            </div>
            <div class="skitem skitems" @click="goToAboutPage('class')">
              <div class="skitemimg">
                <img src="@/assets/images/sj1.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">预约房间数 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.appointmentRoomNumber }}</span
                  >间</div
                >
              </div>
            </div>
          </div>
          <div class="newboxleftitem">
            <div class="skitem skitems" @click="goToAboutPage('roombooking')">
              <div class="skitemimg">
                <img src="@/assets/images/sj5.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">未审批申请 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.waitAuditNumber }}</span></div
                >
              </div>
            </div>
            <div class="skitem skitems" @click="goToAboutPage('roombooking')">
              <div class="skitemimg">
                <img src="@/assets/images/sj6.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">今日提交的审批</div>
                <div class="skitemdesn"
                  ><span>{{ datad.submitAuditNumber }}</span></div
                >
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="newboxmide">
          <div class="newboxleftitem">
            <div class="skitem skitems">
              <div class="skitemimg">
                <img src="@/assets/images/sj3.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">预约在用人数 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.appointmentNumber }}</span
                  >人</div
                >
              </div>
            </div>
            <div class="skitem skitems">
              <div class="skitemimg">
                <img src="@/assets/images/sj1.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">预约房间数 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.appointmentRoomNumber }}</span
                  >间</div
                >
              </div>
            </div>
          </div>
          <div class="newboxleftitem">
            <div class="skitem skitems" @click="goToAboutPage('roombooking')">
              <div class="skitemimg">
                <img src="@/assets/images/sj5.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">未审批申请 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.waitAuditNumber }}</span></div
                >
              </div>
            </div>
            <div class="skitems skitem" @click="goToAboutPage('roombooking')">
              <div class="skitemimg">
                <img src="@/assets/images/sj6.png" alt="" />
              </div>
              <div class="skitemdes">
                <div class="skitemdesitem">今日提交的审批 </div>
                <div class="skitemdesn"
                  ><span>{{ datad.submitAuditNumber }}</span></div
                >
              </div>
            </div>
          </div>
        </div> -->
      </div>
      <div class="mainboxss">
        <div class="chart-containers ssd sssd"
          ><div>近七日数据</div>
          <div class="move"></div>
        </div>
        <div class="chart-containers ssd sssdd"
          ><div>房间使用TOP</div> <div class="move"></div
        ></div>
      </div>
      <div class="mainboxs">
        <div class="csdiv">
          <!--   @change="onChange"
            @select="onSelect"
            @ok="onOk" -->
          <a-range-picker
            v-model="datearry"
            style="width: 250px; margin: 0 24px 24px 0"
            format="YYYY-MM-DD"
            @change="onOk"
            :disabledDate="(current) => dayjs(current).isAfter(dayjs())"
          />
        </div>
        <div ref="chart" class="chart-container"> </div>
        <div ref="charts" class="chart-container ss"></div>
      </div>
      <div class="mainboxs">
        <a-card :style="{ width: '50%' }" title="最新预约申请">
          <template #extra>
            <a-link @click="goToAboutPage('roombooking')">更多</a-link>
          </template>
          <a-table
            ref="userList"
            :loading="loading"
            :columns="columns"
            :data="renderDatas"
            :bordered="false"
            :pagination="false"
          >
            <template #startTime="{ record }">
              {{ record.startTime }}~{{ record.endTime }}
            </template>
          </a-table>
        </a-card>
        <a-card :style="{ width: '50%' }" title="借用最新申请" class="ddddd">
          <template #extra>
            <a-link @click="goToAboutPage('devbooking')">更多</a-link>
          </template>
          <a-table
            ref="userList"
            :loading="loading"
            :columns="column"
            :data="renderData"
            :bordered="false"
            :pagination="false"
          >
            <template #startTime="{ record }">
              {{ record.startTime }}~{{ record.endTime }}
            </template>
            <template #deviceDetail="{ record }">
              {{ formattedData(record.deviceDetail) }}
            </template>
          </a-table>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive, computed } from 'vue';
  import dayjs from 'dayjs';
  import * as echarts from 'echarts';
  import {
    dataOverview,
    appointmentRank,
    dataAppointment,
    appointment,
    appointmentdevice,
  } from '@/api/index';
  import useLoading from '@/hooks/loading';
  import { useRoute, useRouter } from 'vue-router';
  // const loading = ref(true);
  const { loading, setLoading } = useLoading(true);
  // export default {
  //   name: 'dashboardindex', // If you want the include property of keep-alive to take effect, you must name the component
  // };

  // 定义一个方法来格式化数据

  const router = useRouter();

  const goToAboutPage = (name) => {
    // 使用 name 跳转
    router.push({ name: name });
  };
  const formattedData = (deviceDetail: string) => {
    // 假设 deviceDetail 是一个 JSON 字符串，需要先解析为对象
    const parsedData = JSON.parse(deviceDetail);

    // 格式化数据并返回
    return parsedData
      .map((item: any) => `${item.deviceName}*${item.number}`)
      .join(', ');
  };
  const paginations = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '预约时段',
      dataIndex: 'startTime',
      slotName: 'startTime',
      align: 'center',
    },

    {
      title: '预约人',
      dataIndex: 'createUser',
    },
    {
      title: '总人数',
      dataIndex: 'appointmentNumber',
    },
    {
      title: '房间号',
      dataIndex: 'roomName',
    },
  ]);
  const column = computed<TableColumnData[]>(() => [
    {
      title: '预约时段',
      dataIndex: 'startTime',
      slotName: 'startTime',
      align: 'center',
    },

    {
      title: '申请人',
      dataIndex: 'createUser',
    },

    {
      title: '设备内容',
      dataIndex: 'deviceDetail',
      slotName: 'deviceDetail',
    },
  ]);

  const renderData = ref([]);
  const renderDatas = ref([]);
  const fetchDatas = async () => {
    setLoading(true);
    try {
      // if (tableid.value == '1') {
      //   formModel.value.auditStatus = '9';
      // } else {
      //   formModel.value.auditStatus = '1';
      // }

      appointment().then((res) => {
        let list = res.data.list || [];

        renderDatas.value = list;
        paginations.total = res.data.total;
        paginations.current = res.data.current;

        // userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const fetchData = async () => {
    setLoading(true);
    try {
      // if (tableid.value == '1') {
      //   formModel.value.auditStatus = '9';
      // } else {
      //   formModel.value.auditStatus = '1';
      // }

      appointmentdevice({ ...paginations, auditStatus: '1' }).then((res) => {
        let list = res.data.list || [];

        renderData.value = list;
        paginations.total = res.data.total;
        paginations.current = res.data.current;

        // userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onOk = () => {
    // console.log('当前数据', datearry);
    startDate.value = datearry.value[0];
    endDate.value = datearry.value[1];
    dataOverviewdata();
  };
  let datad = ref({});
  let roomData = reactive([
    { roomName: '0', number: 0 },

    // Add more rooms as needed
  ]);
  let dynamicData = reactive([
    { date: '0', roomNumber: 0, number: 0 },
    // { date: '10:00', roomNumber: 83.1, number: 73.4 },
    // { date: '11:00', roomNumber: 86.4, number: 65.2 },
    // { date: '12:00', roomNumber: 72.4, number: 53.9 },
  ]);
  const startDate = ref('');
  const endDate = ref('');
  const datearry = ref([]);

  const dataOverviewdata = async () => {
    loading.value = true;
    try {
      const [overviewRes, rankRes, AppointRes] = await Promise.all([
        dataOverview(),
        appointmentRank(),
        dataAppointment({
          startDate: startDate.value,
          endDate: endDate.value,
        }),
      ]);
      if (overviewRes.data) {
        datad.value = overviewRes.data;
        console.log('获取的数据', overviewRes.data);
      }
      if (rankRes.data) {
        roomData = rankRes.data;
        initCharts(); // 数据加载完成后初始化图表
      }
      if (AppointRes.data) {
        dynamicData = AppointRes.data;
        initChart(); // 数据加载完成后初始化图表
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      loading.value = false;
    }
  };

  const currentTime = ref<string>('');
  // 初始化图表
  let myChart: echarts.ECharts | null = null;
  const chart = ref<HTMLElement | null>(null);
  const charts = ref<HTMLElement | null>(null);

  const initChart = () => {
    if (chart.value) {
      myChart = echarts.init(chart.value);
      let sourceData = dynamicData.map((item) => [
        item.date,
        item.roomNumber,
        item.number,
      ]);
      const option: echarts.EChartsOption = {
        legend: {
          left: '30', // 设置图例在左侧显示
        },
        tooltip: {},
        dataset: {
          source: [
            ['product', '使用房间数', '使用人数'],
            ...sourceData, // 使用动态的数据源
          ],
        },
        xAxis: { type: 'category' },
        yAxis: {
          type: 'value',
          // name: '近7日数据'
        },
        series: [{ type: 'bar' }, { type: 'bar' }],
      };
      myChart.setOption(option);
    }
  };
  const initCharts = () => {
    if (charts.value) {
      myChart = echarts.init(charts.value);
      const option: echarts.EChartsOption = {
        tooltip: {
          trigger: 'axis',
          // axisPointer: {
          //   type: 'shadow',
          // },
          formatter: '{a}<br />{b}: {c}次',
        },
        legend: {
          left: '30',
        },
        xAxis: {
          type: 'category',
          data: roomData.map((item) => item.roomName),
          min: 0, // 设置最小值为 0
          max: 1, // 设置最大值为 1，因为只有两个数据点，所以最大值为 1
          axisLabel: {
            interval: 0, // 强制显示所有标签
          },
        },
        yAxis: {
          type: 'value',
          // name: '房间使用top',
          // max: 100,
        },
        // itemStyle: {
        //   // 设置柱状图的颜色为绿色
        //   color: 'green',
        // },
        series: [
          {
            name: '已预约次数',
            type: 'bar',
            barWidth: '50%', // 每个柱子的宽度
            barMaxWidth: 50, // 每个柱子的最大宽度
            label: {
              show: true,
              position: 'inside',
              formatter: '{c}次',
            },
            data: roomData.map((item) => item.number),
          },
        ],
      };
      myChart.setOption(option);
    }
  };
  // 在组件挂载后获取当前时间
  onMounted(() => {
    // dataOverviewdata();
    //
    updateCurrentTime();
    updateCurrentTimes();
    fetchData();
    fetchDatas();
    dataOverviewdata();
  });

  // 更新当前时间函数
  const updateCurrentTime = () => {
    currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
  };
  // // 当前日期
  const updateCurrentTimes = () => {
    endDate.value = dayjs().format('YYYY-MM-DD');
    startDate.value = dayjs().subtract(7, 'day').format('YYYY-MM-DD');
    datearry.value[0] = startDate.value;
    datearry.value[1] = endDate.value;
    console.log('当前日期', startDate.value, endDate.value, datearry.value);
  };
  // 每秒更新一次时间
  setInterval(updateCurrentTime, 1000);
</script>

<style>
  .mainboxs .ddddd {
    margin-left: 20px !important;
  }
  .mainboxs .arco-card {
    border: none;
    background-color: #f7f8fa !important;
  }
  .mainboxs .arco-card-header {
    border: none;
    background-color: #f7f8fa !important;
  }
  .mainboxss {
    display: flex;
    position: relative;
    font-size: 16px;
  }
  .chart-containers {
    width: 100%;
    /* height: 400px; */
    /* background-color: #f7f8fa !important; */
    /* padding-top: 20px; */
  }
</style>
<style lang="less" scoped>
  .skitems {
    cursor: pointer;
  }
  .move {
    color: blue;
    cursor: pointer;
  }
  .ssd {
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    // background-color: red;
  }
  .chart-container {
    width: 100%;
    height: 400px;
    background-color: #f7f8fa !important;
    padding-top: 20px;
  }
  .sssd {
    padding-left: 25px;
  }
  .sssdd {
    padding-right: 25px;
  }
  .ss {
    margin-left: 20px;
  }

  .newdatebox {
    font-size: 16px;
    // padding: 12px;
    margin-bottom: 24px;
  }
  .newdatebox span {
    font-size: 14px;
    color: #999999;
    display: inline-block;
    margin-left: 20px;
  }
  .newboxmide {
    margin: 5px 0;
    display: flex;
    // padding: 0 24px;
    justify-content: space-between;
  }
  .newboxmide .newboxleftitem {
    width: 775px;
  }
  .newboxmidetwo {
    display: flex;
    // padding: 0 24px;
    margin-top: 24px;
    height: 160px;
    background: #f7f8fa !important;
  }
  .mainbox {
    display: flex;
    padding: 24px 24px;
    flex-direction: column;
  }
  .mainboxs {
    display: flex;
    padding: 24px 24px;
    position: relative;
  }
  .newboxleftitem {
    width: 793px;
    height: 160px;
    // min-width: auto;
    // min-height: auto;
    background: #f7f8fa !important;
    border-radius: 0px 0px 0px 0px;
    display: flex;
    align-content: center;
    justify-content: center;
    margin: 0 10px;
  }
  .skitem {
    display: flex;
    align-content: center;
    justify-content: center;
    margin: 40px auto;
  }
  .skitemimg {
    display: flex;
    align-content: center;
    justify-content: center;
  }
  .skitemdes {
    display: flex;
    flex-direction: column;
    align-content: center;
    justify-content: center;
    margin-left: 30px;
    // margin-top: 20px;
  }
  .skitemdesitem {
    font-size: 16px;
  }
  .skitemdesn {
    font-size: 16px;
  }
  .skitemdesn span {
    font-size: 30px;
    color: #3b75f1;
  }
  .newboxrightitem {
    display: flex;
    //  width: auto;
    //   height: auto;
    width: 793px;
    height: 160px;
    background: #f7f8fa;
    border-radius: 0px 0px 0px 0px;
    align-content: center;
    justify-content: center;
  }
  .container {
    background-color: var(--color-fill-2);
    padding: 16px 20px;
    padding-bottom: 0;
    display: flex;
  }

  .left-side {
    flex: 1;
    overflow: auto;
  }

  .right-side {
    width: 280px;
    margin-left: 16px;
  }

  .panel {
    background-color: var(--color-bg-2);
    border-radius: 4px;
    overflow: auto;
  }
  :deep(.panel-border) {
    margin-bottom: 0;
    border-bottom: 1px solid rgb(var(--gray-2));
  }
  .moduler-wrap {
    border-radius: 4px;
    background-color: var(--color-bg-2);
    :deep(.text) {
      font-size: 12px;
      text-align: center;
      color: rgb(var(--gray-8));
    }

    :deep(.wrapper) {
      margin-bottom: 8px;
      text-align: center;
      cursor: pointer;

      &:last-child {
        .text {
          margin-bottom: 0;
        }
      }
      &:hover {
        .icon {
          color: rgb(var(--arcoblue-6));
          background-color: #e8f3ff;
        }
        .text {
          color: rgb(var(--arcoblue-6));
        }
      }
    }

    :deep(.icon) {
      display: inline-block;
      width: 32px;
      height: 32px;
      margin-bottom: 4px;
      color: rgb(var(--dark-gray-1));
      line-height: 32px;
      font-size: 16px;
      text-align: center;
      background-color: rgb(var(--gray-1));
      border-radius: 4px;
    }
  }
  .csdiv {
    position: absolute;
    top: 50px;
    left: 480px;
    z-index: 99;
  }
  // 这个地方改过
  .responsive .mobile {
    .container {
      display: block;
    }
    .right-side {
      width: 100%;
      margin-left: 0;
      margin-top: 16px;
    }
  }
  .skitemdesitem {
    width: 125px;
  }
</style>
